﻿using System;
using System.Collections.Generic;
using System.Linq;
using Volo.Abp.Domain.Repositories;
using Logistics.Data;
using Logistics.Model;
using Logistics.EntityFrameworkCore;

namespace Logistics
{
    public class PowerManagerRepository :  IPowerManagerRepository
    {
        private readonly IRepository _repository;
        private readonly LogisticsDbContext _logisticsDbContext;

        public PowerManagerRepository(IRepository repository, LogisticsDbContext logisticsDbContext)
        {
            _repository = repository;
            _logisticsDbContext = logisticsDbContext;
        }

        public List<PowerManager> GetListAsync()
        {
            var all = _logisticsDbContext.PowerManager.ToList();
            var list = GetPowerManager(all);
            return list;
        }

        /// <summary>
        /// 获取级联数据集合
        /// </summary>
        /// <returns></returns>
        public List<PowerManager> GetPowerManager(List<PowerManager> PowerManagers)
        {
            var pers = new List<PowerManager>();

            var allPers = PowerManagers;
            var addNodes = allPers.Where(a => Convert.ToInt32(a.Pid) == 0).ToList();
            foreach (var item in addNodes)
            {
                var temPers = new PowerManager
                {
                    Id = item.Id,
                    Name = item.Name,
                    ActionUrl = item.ActionUrl,
                    SortId = item.SortId,
                    Child = GetChildrenNodes(item.Id, allPers)
                };
                pers.Add(temPers);
            }
            return pers;
        }

        /// <summary>
        /// 递归循环，方法调用自身
        /// </summary>
        /// <param name="pid"></param>
        /// <param name="allNodes"></param>
        /// <returns></returns>
        public List<PowerManager> GetChildrenNodes(int pid, List<PowerManager> allNodes)
        {
            var cascaders = new List<PowerManager>();
            var allParentNodes = allNodes.Where(m => Convert.ToInt32(m.Pid) == pid).ToList();
            foreach (var item in allParentNodes)
            {
                var tmpCascader = new PowerManager
                {
                    Id=item.Id,
                    Name = item.Name,
                    ActionUrl = item.ActionUrl,
                    SortId = item.SortId,
                    Child = GetChildrenNodes(item.Id, allNodes)
                };
                cascaders.Add(tmpCascader);
            }
            return cascaders;
        }
    }
}
